package cn.wk.basic.interceptor;

import cn.wk.user.domain.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInfoInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //从作用域中获取消息头
        String token = request.getHeader("token");
        //判断是否存在，不存在的话就进行拦截
        if(StringUtils.isEmpty(token)){
            //跳转页面,axios请求，要给前端响应一个状态，让前端去进行跳转
            resultJson(response);
            //拦截
            return false;
        }
        //通过token去redis中去取用户信息，看起用户信息是否过期
        LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
        if(loginInfo == null){
            //跳转页面,axios请求，要给前端响应一个状态，让前端去进行跳转
            resultJson(response);
            //拦截
            return false;
        }
        //走这里的话重新给redis中添加时长
        redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
        return true;
    }

    /**
     * 给前端响应的话要一个json格式
     * @param response 用其响应
     */
    public void resultJson(HttpServletResponse response) throws IOException {
        //设置响应头和字符码集
        response.setContentType("text/json;charset=utf-8");
        //拿到response的PrintWriter流
        PrintWriter writer = response.getWriter();
        //设置流反映到response对应的位置
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
    }
}
